package inits

import (
	"ViewSrv/conf"
	"ViewSrv/global/model"
	"fmt"
	"github.com/redis/go-redis/v9"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func Init() {
	conf.GetConf()
	MysqlConn()
	RedisConn()
}

func RedisConn() {
	model.RDB = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", conf.Config.Redis.Host, conf.Config.Redis.Port),
		Password: conf.Config.Redis.Password,
		DB:       0,
	})
	if err := model.RDB.Ping(model.Ctx).Err(); err != nil {
		panic(err)
	}
	fmt.Println("redis connect success")
}

func MysqlConn() {
	var err error
	model.DB, err = gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", conf.Config.Mysql.User, conf.Config.Mysql.Password, conf.Config.Mysql.Host, conf.Config.Mysql.Port, conf.Config.Mysql.Database)))
	if err != nil {
		panic(err)
	}
	if err = model.DB.AutoMigrate(&model.Video{}, &model.Type{}, &model.ClassesLike{}, &model.VideoLike{}, &model.VideoLog{}, model.VideoLogLen{}); err != nil {
		panic(err)
	}
	fmt.Println("Auto migrate success")
}
